package com.wenx.throwCamel;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.RouteDefinition;

import java.io.IOException;
import java.net.URLEncoder;

public class JettyThrow {
    public static void main(String[] args) throws Exception {
        CamelContext context = new DefaultCamelContext(); // 1. 创建 CamelContext.
        context.setTracing(true);
        context.start(); // 4. 启动CamelContext.
        context.addRouteDefinition(initRoute());
        Thread.sleep(Integer.MAX_VALUE);  // 为了保持CamelContext处于工作状态，这里需要sleep主线程
        context.stop(); // 最后停止CamelContext
    }

    public static RouteDefinition initRoute(){
        RouteDefinition routeDefinition = new RouteDefinition();
        routeDefinition
                .from("jetty:http://localhost:9080/camel/test2");
        routeDefinition.process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        System.out.println("访问成功!");
                        exchange.getOut().setHeader(Exchange.HTTP_QUERY,"id=111&name=aaa");
                    }
                })
                .doTry()
                .to("http://localhost:8081/demo/hello6?bridgeEndpoint=true")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        System.out.println("回到这里吗");
                    }
                })
//                .doCatch(IOException.class)
//                .process(new Processor() {
//                    @Override
//                    public void process(Exchange exchange) throws Exception {
//                        System.out.println("出现IO异常!");
//                        exchange.getOut().setBody("出现IO异常");
//                    }
//                })
                .doCatch(Exception.class)
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        System.out.println("出现异常!");
                        exchange.getOut().setBody("出现异常");
                        Object object = exchange.getProperty("CamelExceptionCaught");
                        System.out.println("object = " + object);
                        String body = exchange.getIn().getBody(String.class);
                        System.out.println("body = " + body);
                    }
                })
                .endDoTry()
                ;
        return routeDefinition;
    }
}
